/**
 * 
 */
package com.xth8013.as.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.beans.factory.annotation.Value;

/**
 * 
 * @Description: 单点登录过滤器
 * @author: tianhua.xie
 * @Date: 2017年5月14日 上午1:57:19
 * 
 */
@WebFilter(filterName = "SSOFilter",urlPatterns = "/*")
public class SSOFilter implements Filter {


	private FilterConfig filterConfig = null;
	@Value("${sso.cookiename}")
	private String cookiename = "First_SSO_PRJ_ID";
	@Value("${sso.SSOServiceURL}")
	private String SSOServiceURL = null;
	@Value("${sso.SSOLoginPage}")
	private String SSOLoginPage = null;

	/**
	 * 初始化
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

		this.filterConfig = filterConfig;
		if (filterConfig != null) {
			log("SSOFilter:Initializing filter");
		}
	}
	

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		log("SSOFilter:doFilter()");

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		String result = "failed";
		
		String requestUri = request.getRequestURL().toString();

		if (requestUri.indexOf("/BFSwebservice/") != -1 || requestUri.indexOf("/securityController/toLogin") != -1
				|| requestUri.indexOf(".css") != -1 || requestUri.indexOf(".js") != -1
				|| requestUri.indexOf(".jpg") != -1
				|| requestUri.indexOf("/common") != -1 || requestUri.indexOf("/css") != -1
				|| requestUri.indexOf("/script") != -1 || requestUri.indexOf("/image") != -1
				|| requestUri.indexOf("/image_inf") != -1 || requestUri.indexOf("/index.jsp") != -1
				|| requestUri.indexOf("/assets") != -1 || requestUri.indexOf("/css/") != -1
				|| requestUri.indexOf("/easyui_1.5/") != -1 || requestUri.indexOf("/layer/") != -1
				|| requestUri.indexOf("/fonts/") != -1 || requestUri.indexOf(".gif") != -1
				|| requestUri.indexOf(".jpeg") != -1 || requestUri.indexOf("/image") != -1
				|| requestUri.indexOf(".png") != -1 || requestUri.indexOf("/index.jsp") != -1
				|| requestUri.indexOf("/SSOAuth") != -1 || requestUri.endsWith("/com/xth8013/as")
				|| requestUri.endsWith("/com/xth8013/as/")) {
			chain.doFilter(req, res);
		} else {
			System.out.println(requestUri);
			String cookieValue = "";
			Cookie[] diskCookies = request.getCookies();
			if (diskCookies != null) {
				for (int i = 0; i < diskCookies.length; i++) {
					System.out.println(diskCookies[i].getName() + "," + diskCookies[i].getValue());
					if (diskCookies[i].getName().equals(this.cookiename)) {
						cookieValue = diskCookies[i].getValue();
						result = SSOService(cookieValue);
						log("found cookies!");
					}
				}
			}

			// 验证是否登录成功过
			if (result.equals("failed")) {
				response.sendRedirect(this.SSOLoginPage + "?goto=" + requestUri);
			} else if (requestUri.indexOf("logout") > 1) {
				log("logout action!");
				logoutService(cookieValue);
				request.getSession().removeAttribute("loginedUser");
				request.getSession().removeAttribute("loginedUserAccount");
				request.getSession().invalidate();
				response.sendRedirect(this.SSOLoginPage);
			} else {
				request.getSession().setAttribute("loginedUserAccount", result);

				Throwable problem = null;
				try {
					chain.doFilter(request, response);
				} catch (Throwable t) {
					problem = t;
					t.printStackTrace();
				}
				if (problem != null) {
					if ((problem instanceof ServletException))
						throw ((ServletException) problem);
					if ((problem instanceof IOException))
						throw ((IOException) problem);
					// sendProcessingError(problem, res);
				}
			}

		}


	}

	@Override
	public void destroy() {
		
	}

	public FilterConfig getFilterConfig() {
		return this.filterConfig;
	}

	public void setFilterConfig(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}


	private String SSOService(String cookievalue) throws IOException {
		String authAction = "?action=authcookie&cookiename=";
		HttpClient httpclient = new HttpClient();
		GetMethod httpget = new GetMethod(this.SSOServiceURL + authAction + cookievalue);
		try {
			// 判断cookie是否正确
			httpclient.executeMethod(httpget);
			String result = httpget.getResponseBodyAsString();

			return result;
		} catch (Exception e){
			e.printStackTrace();
			return "";
		}finally {
			httpget.releaseConnection();
		}
		// throw new LocalTransactionException();
	}

	private void logoutService(String cookievalue) throws IOException {
		String authAction = "?action=logout&cookiename=";
		HttpClient httpclient = new HttpClient();
		GetMethod httpget = new GetMethod(this.SSOServiceURL + authAction + cookievalue);
		try {
			// 注销登录
			httpclient.executeMethod(httpget);
			httpget.getResponseBodyAsString();
		} finally {
			httpget.releaseConnection();
		}
	}

	public void log(String msg) {
		this.filterConfig.getServletContext().log(msg);
	}
}
